package com.sd.repay.controller;

import com.sd.repay.common.CommonResult;
import com.sd.repay.common.Constants;
import com.sd.repay.service.AgentService;
import com.sd.repay.utils.*;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

/**
 * Created by sd on 2018/08/21
 * 代理商业务控制类
 */
@Controller
@RequestMapping(value = "/agentMgr")
public class AgentController {

    private static final Logger log = LoggerFactory.getLogger(AgentController.class);

    @Autowired
    private AgentService agentService;

    /**
     * 新增代理商
     *
     * @return
     */
    @RequestMapping(value = "/addAgentInfo", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE + ";charset=utf-8")
    @ResponseBody
    public CommonResult addAgentInfo(HttpServletRequest request, @RequestParam Map<String, String> params) {
        log.info("新增代理商开始");

        String oemType = params.get("oemType");
        String agentName = params.get("agentName");
        String parentNo = params.get("parentNo");
        String mobileNo = params.get("mobileNo");
        String loginPwd = params.get("loginPwd");
        String idCardNo = params.get("idCardNo");
        String email = params.get("email");

        try {
            if (StringUtil.isBlank(agentName, mobileNo, loginPwd, idCardNo)) {
                return CommonResult.build(403, "必要参数不能有空值");
            }
            //设置oem类型，默认为“default_repay”
            oemType = StringUtil.isBlank(oemType) ? Constants.DEFAULT_OEM_TYPE : oemType;
            params.put("oemType", oemType);


            if (!Validator.isMobile(mobileNo)) {
                return CommonResult.build(403, "手机号码不合法");
            }
            if (!IdcardUtils.validateCard(idCardNo)) {
                return CommonResult.build(403, "身份证不合法");
            }
            if (StringUtils.isNotBlank(email) && !Validator.isEmail(email)) {
                return CommonResult.build(403, "邮箱不合法");
            }

            //先查询此手机号是否已经注册
            Map<String, Object> oemAgentInfo = agentService.getAgentInfoByMobileAndOem(mobileNo, oemType);
            if (null != oemAgentInfo && !oemAgentInfo.isEmpty()) {
                return CommonResult.build(403, "此手机号已注册");
            }

            //设置代理商节点信息
            parentNo = StringUtil.isBlank(parentNo) ? Constants.DEFAULT_PARENT_AGENT_NO : parentNo;
            params.put("parentNo", parentNo);

            String agentNo = WebUtil.nextAgentNo();
            String agentNode = agentNo;
            int agentLevel = 1;
            String oneAgentNo = agentNo;

            if (!Constants.DEFAULT_PARENT_AGENT_NO.equals(parentNo)) {

                Map<String, Object> parentAgentMap = agentService.getAgentInfoByAgentNo(agentNo);
                log.info("代理商名：{}注册上级代理商：{}信息：{}", new Object[]{agentName, parentNo, JsonUtil.objectToJson(parentAgentMap)});
                if (null == parentAgentMap || parentAgentMap.isEmpty()) {
                    return CommonResult.build(403, "父级代理商信息不存在");
                }
                agentNode = StringUtil.filterNull(parentAgentMap.get("agent_node")) + "-" + agentNo;
                agentLevel = Integer.parseInt(StringUtil.filterNull(parentAgentMap.get("agent_level"))) + 1;
                oneAgentNo = StringUtil.filterNull(parentAgentMap.get("one_agent_no"));
            }
            params.put("agentNo", agentNo);
            params.put("agentNode", agentNode);
            params.put("agentLevel", agentLevel + "");
            params.put("oneAgentNo", oneAgentNo);

            //设置密码
            loginPwd = DES3Coder.encryptToString(loginPwd);
            params.put("loginPwd", loginPwd);

            //保存代理商
            int count = agentService.addAgentInfo(params);
            log.info("代理商名称：{}新增代理商信息影响的行数：", new Object[]{agentName, count});
            if (count < 1) {
                return CommonResult.build(403, "新增代理商失败，请稍候再试");
            }

        } catch (Exception e) {
            e.printStackTrace();
            log.info(agentName + "新增代理商异常：" + e);
            return CommonResult.build(403, "新增代理商失败，请稍候再试");
        }
        return CommonResult.ok();
    }
}
